package com.googlecode.synccontacts.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.googlecode.synccontacts.dao.entity.Account;

/**
 * User: volkovma@inbox.ru
 * Date: 15.02.11
 * DAO Util
 */
public class DAOUtil {
    private static final boolean WRITEDB = true;
    private static final boolean READONLYDB = false;
    private Context context;

    /**
     * Конструктор
     *
     * @param context
     */
    public DAOUtil(Context context) {
        this.context = context;
    }

    /**
     * Сохранение аккаутна для соц.сети
     *
     * @param account
     */
    public long saveAccount(Account account) {
        SQLiteDatabase db = getDataBase(WRITEDB);
        ContentValues row = new ContentValues();
        row.put(DbOpen.SOC_NET, account.getSocialNetworkType());
        row.put(DbOpen.LOGIN, account.getLogin());
        row.put(DbOpen.PASSW, account.getPass());
        long result = db.insert(DbOpen.TABLE_ACCOUNTS, null, row);
        db.close();
        return result;
    }

    /**
     * Получение аккаунта для соцсети
     *
     * @param socNetType тип сети
     * @return
     */
    public Account getAccount(int socNetType) {
        Account result = new Account();
        SQLiteDatabase db = getDataBase(READONLYDB);
        Cursor cur = db.query(DbOpen.TABLE_ACCOUNTS, DbOpen.ACCOUNT_COLUMNS, DbOpen.SOC_NET + " = " + socNetType, null, null,
                null, null, null);
        cur.moveToNext();
        result.setSocialNetworkType(socNetType);
        result.setLogin(cur.getString(cur.getColumnIndex(DbOpen.LOGIN)));
        result.setPass(cur.getString(cur.getColumnIndex(DbOpen.PASSW)));
        db.close();
        return result;
    }

    /**
     * Создаем (открываем) БД.
     *
     * @return
     */
    private SQLiteDatabase getDataBase(boolean write) {
        DbOpen dbOpen = new DbOpen(context);
        if (write) {
            return dbOpen.getWritableDatabase();
        } else {
            return dbOpen.getReadableDatabase();
        }
    }
}
